package edu.hunau.recommend.controller.admin;

import edu.hunau.recommend.advice.AdminPermission;
import edu.hunau.recommend.common.MD5Utils;
import edu.hunau.recommend.common.ResultCodeEnum;
import edu.hunau.recommend.exception.RecommendBusinessException;
import edu.hunau.recommend.service.UserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Controller;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.servlet.ModelAndView;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;

/**
 * @author name
 * @creater 2022-09-13-11:12
 */
@Controller
@RequestMapping("/admin/admin")
public class AdminManagerController {

    //使用SpringEL表达式, 读取配置文件中的数据为属性赋值
    @Value("${admin.email}")
    private String email;
    @Value("${admin.encryptyPassword}")
    private String password;

    @Autowired
    private HttpServletRequest request;

    public static final String ADMIN_NAME_SESSION = "admin_name_session";

    @RequestMapping("/loginPage")
    public String loginPage(){
        return "/admin/admin/login";
    }

    @RequestMapping("/login")
    public String login(@RequestParam(name = "email") String email,@RequestParam(name = "password") String password){

        if(!StringUtils.hasLength(email) || !StringUtils.hasLength(password)){
            throw new RecommendBusinessException(ResultCodeEnum.NULL_POINT);
        }
        if(email.equals(this.email) && MD5Utils.md5(password).equals(this.password)){
                //登录成功, 将管理的Email封装到Session中
                request.getSession().setAttribute(ADMIN_NAME_SESSION, email);

                //登录成功   redirect表示重定向
            return "redirect:/admin/admin/index";

        }else{
            throw new RecommendBusinessException(ResultCodeEnum.LOGIN_FAIL);
        }

    }


    @Resource
    private UserService userService;


    //表示index的请求需要进行权限校验
    @AdminPermission
    //@AdminPersion(produceType = "application/json")
//    @ResponseBody
    @RequestMapping("/index")
   public ModelAndView index(){
       ModelAndView mv = new ModelAndView("/admin/admin/index");
        int count = userService.countAllUser();
        //封装数据
        mv.addObject("CONTROLLER_NAME","admin");
        mv.addObject("ACTION_NAME","index");
        mv.addObject("userCount",count);
        return mv;
   }
}
